﻿using Microsoft.TeamFoundation.VersionControl.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TFSUtilLibrary
{
    class Branch
    {
        public void LoadBranches(string uri)
        {
            Connection con = new Connection(uri);
            if (!con.ConnectToTFS())
                Common.Messages.ThrowNonConnect();

            /// The following code is adapted from here:
            /// http://pascallaurin42.blogspot.co.uk/2012/08/tfs-queries-listing-all-branches.html
            var versionControl = con.VCS;
 
            versionControl.QueryRootBranchObjects(RecursionType.Full)
                .Where(b => !b.Properties.RootItem.IsDeleted)
                .Select(s => new
                {
                    Project = s.Properties.RootItem.Item
                        .Substring(0, s.Properties.RootItem.Item.IndexOf('/', 2)),
                    Properties = s.Properties,
                    DateCreated = s.DateCreated,
                    ChildBranches = s.ChildBranches
                })
                .Select(s => new
                {
                    s.Project,
                    Branch = s.Properties.RootItem.Item.Replace(s.Project, ""),
                    Parent = s.Properties.ParentBranch != null ?
                        s.Properties.ParentBranch.Item.Replace(s.Project, "") : "",
                    Version = (s.Properties.RootItem.Version as ChangesetVersionSpec)
                        .ChangesetId,
                    DateCreated = s.DateCreated,
                    Owner = s.Properties.Owner,
                    ChildBranches = s.ChildBranches
                        .Where (cb => !cb.IsDeleted)
                        .Select(cb => new
                        {
                            Branch = cb.Item.Replace(s.Project, ""),
                            Version = (cb.Version as ChangesetVersionSpec).ChangesetId
                        })
                })
                .OrderBy(s => s.Project).ThenByDescending(s => s.Version);


        }
    }
}
